<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons')
import resize from './mixins/resize'
import { getToken } from '@/utils/auth'
import { getAllChannel } from '@/api/charts'
import { format2Date } from '@/utils'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null,
      listQuery: {
        token: undefined,
        date: undefined
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.listQuery.date = format2Date(new Date(), 'yyyy-MM-dd')
      this.listQuery.token = getToken()
      getAllChannel(this.listQuery).then(response => {
        this.chart.setOption({
          title: {
            text: '购票渠道占比',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          legend: {
            left: 'center',
            top: 'bottom',
            data: response.name
          },
          toolbox: {
            show: true,
            feature: {
              saveAsImage: { show: true }
            }
          },
          series: [
            {
              name: '购票方式',
              type: 'pie',
              radius: [20, 110],
              roseType: 'area',
              itemStyle: {
                borderRadius: 5
              },
              data: response.data
            }
          ]
        })
      })
    }
  }
}
</script>
